<template>
    <ContentWrap>
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="70px" @submit.native.prevent>
            <el-form-item label="预约人" prop="name">
                <el-input v-model="queryParams.name" class="!w-240px" clearable
                          placeholder="请输入预约人名称" @keyup.enter="handleQuery"/>
            </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" class="!w-240px" clearable
                      placeholder="请输入手机号" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="房间号" prop="roomNum">
            <el-input v-model="queryParams.roomNum" class="!w-240px" clearable
                      placeholder="请输入房间号" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
            <el-select v-model="queryParams.schoolId" placeholder="请选择" class="!w-240px" filterable default-first-option clearable>
              <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预约状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable class="!w-240px">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.YXT_SUBSCRIBE_STATUS)" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="预约时间" prop="subscribeTime">
            <el-date-picker v-model="queryParams.subscribeTime" unlink-panels value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                            start-placeholder="起始日期" end-placeholder="结束日期" class="!w-380px"/>
          </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery">
                    <Icon class="mr-5px" icon="ep:search"/>
                    搜索
                </el-button>
                <el-button @click="resetQuery">
                    <Icon class="mr-5px" icon="ep:refresh"/>
                    重置
                </el-button>
                <!--<el-button v-hasPermi="['yxt:subscribe:open-door']" type="success" @click="remoteOpenDoor"
                           :disabled="isEmpty(selectKeys)">
                    <Icon class="mr-5px" icon="ep:refresh"/>
                    远程开门
                </el-button>-->
                <el-button v-hasPermi="['yxt:subscribe:cancel']" type="danger" @click="cancel"
                           :disabled="isEmpty(selectKeys)">
                    <Icon class="mr-5px" icon="ep:refresh"/>
                    取消预约
                </el-button>
                <el-button type="success" plain @click="handleExport" :loading="exportLoading">
                    <Icon icon="ep:download"/>
                    导出
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>

    <ContentWrap>
        <el-table ref="tableRef" v-loading="loading" :data="list" @selection-change="selectionChange">
            <el-table-column type="selection"/>
            <el-table-column label="头像" prop="avatar" width="50">
                <template #default="scope">
                    <div style="width: 36px; height: 36px">
                        <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" preview-teleported hide-on-click-modal/>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="预约人" prop="memberName" min-width="150"/>
            <el-table-column label="归属学校" prop="schoolName" min-width="150"/>
            <el-table-column label="手机号" prop="mobile" min-width="150"/>
            <el-table-column label="类型" prop="type">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_USER_TYPE" :value="scope.row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="琴房类型" prop="roomTypeName" min-width="150"/>
            <el-table-column label="教学楼" prop="buildingName" min-width="150"/>
            <el-table-column label="楼层" prop="floor" min-width="150"/>
            <el-table-column label="房间号" prop="number" min-width="150"/>
            <el-table-column :formatter="dateFormatter" label="预约时间" prop="startTime"
                             min-width="180"/>
            <el-table-column label="预约时长" prop="keepTime" min-width="150"/>
            <el-table-column label="实际时长" prop="actualTime" min-width="150"/>
            <el-table-column label="预约状态" prop="status">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_SUBSCRIBE_STATUS" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime"
                             min-width="180"/>
        </el-table>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                    :total="total" @pagination="getList"/>
    </ContentWrap>

</template>

<script lang="ts" setup>
import {dateFormatter} from '@/utils/formatTime'
import {useSubscribeApi} from "@/api/yxt/subscribe";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {ElTable} from "element-plus";
import {isEmpty} from "lodash-es";
import {useConfirm, useMessage} from "@/components/Notice";
import * as XLSX from 'xlsx/dist/xlsx.full.min'
import {getTenantId} from "@/utils/auth";
import {useSchoolApi} from "@/api/yxt/school";

const {t} = useI18n() // 国际化
defineOptions({name: 'YxtSubscribe'})

const tenantId = getTenantId();
const subscribeApi = useSubscribeApi();
const schoolApi = useSchoolApi();

const loading = ref(true)
const total = ref(0)
const list = ref([])
const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    name: '',
    mobile: '',
    roomNum: '',
    schoolId: '',
    status: '',
    subscribeTime: [],
})
const queryFormRef = ref()
const tableRef = ref<InstanceType<typeof ElTable>>();
const selectKeys = ref<Array<any>>([]);
const exportLoading = ref(false)
const multipleSelection = ref<Array<any>>([])
const schools = ref<Array<any>>([])

function selectionChange(list: Array<any>) {
    selectKeys.value = [];
    list.forEach((item) => selectKeys.value.push(item.id));
    multipleSelection.value = list;

}

const getList = async () => {
    loading.value = true
    try {
        const data = await subscribeApi.getSubscribePage(queryParams)
        list.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
}

const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
}

const remoteOpenDoor = () => {
    if (isEmpty(selectKeys.value)) return;

    useConfirm("确认对所选预约单远程开门?", () => {
        subscribeApi.remote(selectKeys.value).then(() => {
            getList().finally(() => useMessage("请求已发送"));
        });
    })
}

const cancel = () => {
    if (isEmpty(selectKeys.value)) return;

    useConfirm("确认对所选预约单取消预约?", () => {
        subscribeApi.cancelBatch(selectKeys.value).then(() => {
                getList();
                useMessage("取消成功", "success")
            }
        )
    })
}


const handleExport = () => {
    useConfirm(t("common.exportMessage"), async () => {
        exportLoading.value = true
        try {
            if (list.value.length == 0) {
                useMessage("没有可导出数据", "warning");
                return;
            }
            const exportData = multipleSelection.value.length > 0 ? multipleSelection.value
                : await useSubscribeApi().noPageList(queryParams);
            const formatData = exportData.map(formatSubData)
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formatData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "选中数据");

            // 生成文件
            XLSX.writeFile(wb, "预约列表数据.xlsx");
        } finally {
            exportLoading.value = false
        }
    });
}

const formatSubData = (item) => {
    return {
        // "头像": item.avatar,
        "预约人": item.memberName,
        "归属学校": item.schoolName,
        "手机号": item.mobile,
        "类型": item.type == 0 ? "学生" : "老师",
        "琴房类型": item.roomTypeName,
        "教学楼": item.buildingName,
        "楼层": item.floor,
        "房间号": item.number,
        "预约时间": formatDateTime(item.startTime),
        "预约时长": item.keepTime,
        "实际时长": item.actualTime,
        "预约状态": getSubStatus(item.status),
        "创建时间": formatDateTime(item.createTime)
    }
}
const getSubStatus = (status: any) => {
    let subStatus = '';
    switch (status) {
        case 1:
            subStatus = '未开始';
            break;
        case 2:
            subStatus = '待签到';
            break;
        case 3:
            subStatus = '进行中';
            break;
        case 4:
            subStatus = '已完成';
            break;
        case 5:
            subStatus = '已取消';
            break;
        case 6:
            subStatus = '爽约';
            break;
        default:
            subStatus = '未知';
    }
    return subStatus;
}

//时间戳格式化为时间
const formatDateTime = (timestamp: any) => {
    const formattedDate = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 使用 24 小时制
    }).format(new Date(timestamp));
    return formattedDate;
}

onMounted(async () => {
    getList();
    schools.value = await schoolApi.getSimpleList();
})
</script>
